package cn.zfs.fast.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @ClassName: HttpClientUtils
 * @Author: ZFS
 * @Date: 2018/10/12 13:26
 */
@Slf4j
@Component
public class HttpClientUtils {

    /**
     * swagger 基础API访问
     *
     * @return string
     * @throws IOException IOException
     */
    public String requestUrl(String url) throws Exception {
        // 设置Cookie
        CookieStore cookieStore = new BasicCookieStore();
        // 生成客户端
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore) // 设置cookie
                .build();
        // 生成请求
        HttpRequestBase httpRequestBase = new HttpRequestBase() {
            @Override
            public String getMethod() {
                return "GET";
            }
        };
        httpRequestBase.setURI(URI.create(url));
        httpRequestBase.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
        httpRequestBase.setHeader("Accept","*/*");
        httpRequestBase.setHeader("Accept-Encoding","gzip, deflate, br");
        httpRequestBase.setHeader("Accept-Language","zh-CN,zh;q=0.9");
        httpRequestBase.setHeader("Connection","keep-alive");

        HttpResponse httpResponse = httpClient.execute(httpRequestBase);
        String responseEntityStr = EntityUtils.toString(httpResponse.getEntity());
        ((CloseableHttpResponse) httpResponse).close();
        log.info("响应数据:{}", responseEntityStr);
        return responseEntityStr;
    }
}
